#include "comm.hpp"
#include <iostream>
#include <cstdlib>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
    // 创建管道
    int n = mkfifo(FIFO_FILE, MODE);
    if (n == -1) 
    {
        perror("mkfifo");
        exit(FIFO_CREATE_ERR);
    }

    // 打开管道
    int fd = open(FIFO_FILE, O_RDONLY);
    if (fd < 0)
    {
        perror("open");
        exit(FIFO_DELETE_ERR);
    }

    // 开始通信
    while (true)
    {
        char buffer[BUFFERSIZE];  // 接收字符串数据
        buffer[0] = 0;

        int RedNum = read(fd, buffer, sizeof(buffer));
        if (RedNum > 0) {
            buffer[RedNum] = 0;
            std::cout << "client say [" << buffer << "]" << std::endl;
        }
        else if (RedNum == 0)
        {
            std::cout << "client quit" << std::endl;
            break;
        }
        else break;
    }
    close(fd);

    // 删除管道
    int m = unlink(FIFO_FILE);
    if (m == -1)
    {
        perror("unlink");
        exit(FIFO_DELETE_ERR);
    }    

    return 0;
}